package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 登录校验的方法
     * @param paramMap
     * @return
     */
    public Map<String,String> login(Map<String, String> paramMap) {
        //1. 获取请求参数
        String verificationCode = paramMap.get("verificationCode");
        String username = paramMap.get("username");
        String password = paramMap.get("password");
        String uuid = paramMap.get("uuid");

        //2. 校验用户名与密码是否为空，如果为空直接抛出异常
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw  new BusinessException("用户名或者密码不能为空");
        }

        //3. 判断验证码是否正确
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(code)||!code.equalsIgnoreCase(verificationCode)){
            throw  new BusinessException("验证码错误");
        }

        //4. 判断用户名与密码是否正确
        QueryWrapper<Admin> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if(admin==null||!admin.getPassword().equals(SecureUtil.md5(password))){
            throw  new BusinessException("用户名或者密码错误");
        }
        //5. 生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",admin.getId());
        claims.put("username",admin.getUsername());
        String token = JwtUtils.getToken(claims);

        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("token",token);
        return resultMap;


    }

    /**
     * 查询用户的基本信息
     * @return
     */
    public AdminVo profile() {
        Long adminId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(adminId);
        AdminVo adminVo = new AdminVo();
        adminVo.setId(admin.getId()+"");
        adminVo.setUsername(admin.getUsername());
        adminVo.setAvatar(admin.getAvatar());
        return adminVo;
    }
}
